16. Exercise: Use the Repository
L9 31 Use The Repository SC
Update: You must have learned in "Lesson 1: App Architecture (Persistence)" that creating your own scope is no longer recommended by Google. The recommended way is to use a lifecycle-aware coroutine scope
ViewModelScope, provided by the Architecture components.
Similarly, in theDevByteViewModel.ktfile we will not require theviewModelJobobject, own scopeviewModelScope, and the overriddenonCleared()function. Instead, use the defaultviewModelScope.
Now it’s your turn to complete this exercise yourself.
To finish offline caching, you'll need to integrate the repository into your view model.
1. Delete the code that will be replaced by the repository:
In DevByteViewModel, delete _playlist, playlist variables, the init block, and refreshDataFromNetwork() function. We'll replace this code with the repository.
2. Create the database singleton.
Define a database variable and assign it to getDatabase(), passing the application.
private val database = getDatabase(application)
3. Then create your repository.
Define val videosRepository and assign it to a VideosRepository using the database singleton.
private val videosRepository = VideosRepository(database)
4. Refresh the videos using the repository.
Create an init block and launch a coroutine to call videosRepository.refreshVideos().
viewModelScope.launch {
videosRepository.refreshVideos()
}
5. Create the playlist.
Get videos LiveData from the repository and assign it to a playlist variable.
val playlist = videosRepository.videos
That’s it! You’ve implemented that offline cache our app needed. It's so nice to see those DevBytes even faster than before!
If you want to start at this step, you can download this exercise code from: Step.06-Exercise-Use-the-Repository.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here Step.06-Solution-Use-the-Repository or using this git diff
Task Description:
Check the steps below as you implement them to complete this exercise
Task Feedback:
Amazing! These videos display so much faster now.
There’s one more task waiting for you - we want to pre-fetch videos even when users aren’t in the app. Check out the next videos for more!